import os
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext


class TextEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("简单文本编辑器")
        self.root.geometry("800x600")

        # 当前文件路径
        self.current_file = None

        # 创建菜单栏
        self.create_menu()

        # 创建文本编辑区域
        self.create_text_area()

        # 创建状态栏
        self.create_status_bar()

        # 绑定事件
        self.bind_events()

        # 设置初始状态
        self.update_status_bar()

    def create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self.root)

        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(
            label="新建", command=self.new_file, accelerator="Ctrl+N")
        file_menu.add_command(
            label="打开", command=self.open_file, accelerator="Ctrl+O")
        file_menu.add_command(
            label="保存", command=self.save_file, accelerator="Ctrl+S")
        file_menu.add_command(label="另存为", command=self.save_as_file)
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.root.quit)
        menubar.add_cascade(label="文件", menu=file_menu)

        # 编辑菜单
        edit_menu = tk.Menu(menubar, tearoff=0)
        edit_menu.add_command(
            label="剪切", command=self.cut_text, accelerator="Ctrl+X")
        edit_menu.add_command(
            label="复制", command=self.copy_text, accelerator="Ctrl+C")
        edit_menu.add_command(
            label="粘贴", command=self.paste_text, accelerator="Ctrl+V")
        menubar.add_cascade(label="编辑", menu=edit_menu)

        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="关于", command=self.show_about)
        menubar.add_cascade(label="帮助", menu=help_menu)

        self.root.config(menu=menubar)

    def create_text_area(self):
        """创建文本编辑区域"""
        # 创建滚动文本区域
        self.text_area = scrolledtext.ScrolledText(
            self.root, wrap=tk.WORD, undo=True)
        self.text_area.pack(expand=True, fill='both', padx=5, pady=5)

        # 设置字体
        self.text_area.config(font=("Courier New", 12))

    def create_status_bar(self):
        """创建状态栏"""
        self.status_bar = tk.Label(
            self.root, text="就绪", bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def bind_events(self):
        """绑定事件"""
        # 绑定键盘快捷键
        self.root.bind("<Control-n>", lambda event: self.new_file())
        self.root.bind("<Control-o>", lambda event: self.open_file())
        self.root.bind("<Control-s>", lambda event: self.save_file())

        # 绑定文本变化事件
        self.text_area.bind("<<Modified>>", self.on_text_modified)

    def on_text_modified(self, event=None):
        """文本修改事件处理"""
        if self.text_area.edit_modified():
            self.update_status_bar()
            self.text_area.edit_modified(False)

    def update_status_bar(self):
        """更新状态栏"""
        if self.current_file:
            filename = os.path.basename(self.current_file)
            self.status_bar.config(
                text=f"文件: {filename} | 字符数: {len(self.text_area.get('1.0', tk.END))}")
        else:
            self.status_bar.config(text="未命名 | 字符数: 0")

    def new_file(self):
        """新建文件"""
        if self.text_area.edit_modified():
            response = messagebox.askyesnocancel("保存", "是否保存当前文件?")
            if response is None:  # 取消
                return
            if response:  # 是
                if not self.save_file():
                    return

        self.text_area.delete('1.0', tk.END)
        self.current_file = None
        self.root.title("简单文本编辑器")
        self.update_status_bar()

    def open_file(self):
        """打开文件"""
        if self.text_area.edit_modified():
            response = messagebox.askyesnocancel("保存", "是否保存当前文件?")
            if response is None:  # 取消
                return
            if response:  # 是
                if not self.save_file():
                    return

        file_path = filedialog.askopenfilename(
            defaultextension=".txt",
            filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
        )

        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
                    self.text_area.delete('1.0', tk.END)
                    self.text_area.insert('1.0', content)
                    self.current_file = file_path
                    self.root.title(f"简单文本编辑器 - {os.path.basename(file_path)}")
                    self.update_status_bar()
            except Exception as e:
                messagebox.showerror("错误", f"无法打开文件: {str(e)}")

    def save_file(self):
        """保存文件"""
        if not self.current_file:
            return self.save_as_file()

        try:
            content = self.text_area.get('1.0', tk.END)
            with open(self.current_file, 'w', encoding='utf-8') as file:
                file.write(content)
            self.text_area.edit_modified(False)
            self.update_status_bar()
            return True
        except Exception as e:
            messagebox.showerror("错误", f"无法保存文件: {str(e)}")
            return False

    def save_as_file(self):
        """另存为文件"""
        file_path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
        )

        if file_path:
            self.current_file = file_path
            self.root.title(f"简单文本编辑器 - {os.path.basename(file_path)}")
            return self.save_file()
        return False

    def cut_text(self):
        """剪切文本"""
        self.text_area.event_generate("<<Cut>>")

    def copy_text(self):
        """复制文本"""
        self.text_area.event_generate("<<Copy>>")

    def paste_text(self):
        """粘贴文本"""
        self.text_area.event_generate("<<Paste>>")

    def show_about(self):
        """显示关于对话框"""
        messagebox.showinfo(
            "关于", "简单文本编辑器 v1.0\n\n一个使用Python Tkinter开发的简单文本编辑器。")


if __name__ == "__main__":
    root = tk.Tk()
    app = TextEditor(root)
    root.mainloop()
